/*
 程序作者: 戴雨晨
 完成日期: 2014年2月28日
 章    节: 第 3 章
 题    号: 习题2
 题    目: 在人口统计中，按如下的公式计算出生率和死亡率：
           出生率＝8000/ 100000＝0.08  死亡率＝6000/ 100000＝0.06
           设计一个人口类Population，它能存储某年的人数、出生的人
           数和死亡人数。其函数成员能返回出生率和死亡率。编写一个
           完整的程序检验该类的正确性。
           输入有效性检验：人数不能小于1 ，出生人数和死亡人数不能
           为负数。
*/
#include <iostream>
#include <vector>
using namespace std;
struct people
	{
		int year,people,birth,death;
	};
class Population
{
private:
	vector<struct people> data;
public:
	bool setdata(struct people buffer)
	{
			if(buffer.people>=1&&buffer.birth>=0&&buffer.death>=0)
			{
				data.push_back(buffer);
				return true;
			}
			else
				return false;
	}
	float get_birthrate(int year)
	{
		float ans;
		vector<struct people>::iterator pointer;
		if(data.empty())
			return -0.0001;
		for(pointer=data.begin();pointer!=data.end();pointer++)
			if(pointer->year==year)
				break;
		if(pointer!=data.end())
			ans=(float)pointer->birth/(float)pointer->people;
		else
			ans=-0;
		return ans;
	}
	float get_deathrate(int year)
	{
		float ans;
		vector<struct people>::iterator pointer;
		if(data.empty())
			return -0.0001;
		for(pointer=data.begin();pointer<data.end();pointer++)
			if(pointer->year==year)
				break;
		if(pointer!=data.end())
			ans=(float)pointer->death/(float)pointer->people;
		else
			ans=-0;
		return ans;
	}
};
int main()
{
	Population pop;
	string operation;
	struct people temp;
	int year;
	float ans;
	while(1)
	{
		cin>>operation;
		if(operation=="exit")
			break;
		else if(operation=="add")
		{
			cout<<"Input the year, the population, the number of birth and the number of dead"<<endl;
			cin>>temp.year>>temp.people>>temp.birth>>temp.death;
			if(pop.setdata(temp))
				cout<<"Adding complete"<<endl;
			else
				cout<<"Invalid data"<<endl;
		}
		else if(operation=="deathrate")
		{
			cout<<"Please input the year:";
			cin>>year;
			ans=(float)pop.get_deathrate(year);
			if(ans!=-0.0001)
				cout<<"The deathrate of the year is "<<ans<<"."<<endl;
			else
				cout<<"Can't find the year "<<year<<"."<<endl;
		}
		else if(operation=="birthrate")
		{
			cout<<"Please input the year:";
			cin>>year;
			ans=(float)pop.get_birthrate(year);
			if(ans!=-0.0001)
				cout<<"The birthrate of the year is "<<ans<<"."<<endl;
			else
				cout<<"Can't find the year "<<year<<"."<<endl;
		}
		else
		{
			cout<<"Operation error!"<<endl;
		}
	}
	return 0;
}
